<template>
    <a-button type="primary" @click="showModal('add', {})">添加</a-button>
    <a-table 
        :dataSource="dataSource" 
        :columns="columns" 
        :loading="isLoading"
        :row-selection="rowSelection" 
        :rowKey="record => record.id">
        <template #headerCell="{title, column}">
            <slot name="headerCell" v-bind="{ title, column }"></slot>
        </template>
        <template #bodyCell="{text, record, index, column}">
            <slot name="bodyCell" v-bind="{text, record, index, column}"></slot>
                <a-space v-if="column.key === 'action'">
                    <a-button type="primary" size="small" @click="showModal('edit', record)">
                        <ant-icon-edit-outlined />编辑
                    </a-button>
                    <a-popconfirm title="确定删除吗？" okText="确定" cancelText="取消" @confirm="deleteRecord(record)">
                        <a-button type="primary" danger size="small">
                            <ant-icon-delete-outlined />删除
                        </a-button>
                    </a-popconfirm>
                </a-space>
        </template>
    </a-table>
    <a-modal v-model:open="open" :title="modalTitle" @cancel="open = false" @ok="handleSubmit" okText="提交">
        <a-form 
            :model="modalFormData" 
            name="modalForm"
            ref="modalFormRef" 
            autocomplete="off"
            labelAlign="right"
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 20 }"
        >
            <slot v-for="item, index in Object.keys(modalFormData)" :key="index" :name="item">
                <a-form-item :label="item" :name="item" v-bind="validateInfos[item]" v-if="item !== 'id'">
                    <a-input v-model:value="Object.values(modalFormData)[index]" :disabled="item === 'id'" />
                </a-form-item>
            </slot>
        </a-form>
    </a-modal>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue';
import { Form } from 'ant-design-vue';
import { useMenusStore } from '@/stores/menus';

const useForm = Form.useForm
const menusStore = useMenusStore()

const isLoading = ref(false)
const dataSource = ref([])
const columns = defineModel({ type: Array, default: () => [] });

const { proxy } = getCurrentInstance()

const props = defineProps({
    apiObj: {
        type: Object,
        default: () => ({})
    },
    data: {
        type: Array,
        default: () => []
    }
})
const getData = async () => {
    dataSource.value = props.data
    if (dataSource.value.length === 0){
        isLoading.value = true
        const res = await props.apiObj.getMenuAPI()
        dataSource.value = filterData(res.data.value)
        isLoading.value = false
        menusStore.setMenus(res.data.value)
    }
}

onMounted(() => {
    getData()
})

// 删除记录
const deleteRecord = async (record) => {
    try {
        await props.apiObj.deleteMenuDetailAPI(record.id)
        dataSource.value = dataSource.value.filter(item => item.id !== record.id)
        await getData()
        proxy.$message.success('删除成功')
    } catch (error) {
        console.log(error);
        proxy.$message.error('删除失败')
    } 
}
// 整理数据格式
const filterData = (data) => {
    return data.map(item => {
        return {
            ...item,
            key: item.id,
            title: item.name,
            description: item.path,
            children: item.children && item.children.length > 0 ? filterData(item.children) : undefined
        }
    })
}

const rowSelection = ref({
  checkStrictly: false,
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
  },
  onSelect: (record, selected, selectedRows) => {
    console.log(record, selected, selectedRows);
  },
  onSelectAll: (selected, selectedRows, changeRows) => {
    console.log(selected, selectedRows, changeRows);
  },
});

// modal相关
const open = ref(false);
const modalTitle = ref('');
const modalType = ref('add');
const modalFormData = defineModel('modalFormData')
const rulesRef = defineModel('rulesRef')
// 打开modal
const showModal = (type, record) => {
    open.value = true
    modalType.value = type
    modalTitle.value = type === 'add' ? '添加' : '编辑'
    proxy.$emit('showModalEvent', type, record)
}
// 表单相关
const { resetFields, validate, validateInfos } = useForm(modalFormData, rulesRef, {
  onValidate: (...args) => args,
});

// 提交表单
const handleSubmit = async () => {
    try {
        await validate()
        open.value = false
        proxy.$emit('submitEvent', modalType.value, modalFormData.value)
    } catch (error) {
        console.log(error);
    }
}

defineEmits(['showModalEvent', 'submitEvent'])
defineExpose({resetFields, validate, validateInfos, getData})
</script>